package com.mzba.zxdlyllp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;

import com.actionbarsherlock.view.MenuItem;
import com.mzba.zxdlyllp.db.BookTable;
import com.mzba.zxdlyllp.db.BookTable.BookEntity;
import com.mzba.zxdlyllp.utils.AppContext;
import com.mzba.zxdlyllp.utils.HttpUtils;
import com.mzba.zxdlyllp.utils.StringUtil;
import com.mzba.zxdlyllp.utils.UICore;
import com.slidingmenu.lib.SlidingMenu;

/**
 * 
 * @author 06peng
 *
 */
public class BooksActivity extends BaseFragmentActivity implements Callback{
	
	public ArrayList<BookEntity> list;
	private FragmentTransaction fragmentTransaction;
	private SlidingMenu sm;
	Handler handler;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_frame_content);
		setBehindContentView(R.layout.fragment_menu_frame);
		handler = new Handler(this);
		initSlidingMenu();
		actionBar.show();
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayUseLogoEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setLogo(R.drawable.hamburger);
		UICore.eventTask(this, this, 0, null, true);
	}
	
	@Override
	public void execute(int mes, Object obj) {
		try {
			BookTable bt = new BookTable(this);
			list = bt.get();
			if (list != null && !list.isEmpty()) {
				fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
				Fragment bookSliding = new BookSlidingSettingFragment();
				fragmentTransaction.replace(R.id.menu_frame, bookSliding);
				fragmentTransaction.replace(R.id.content, new BookFragmentItem(list.get(0).getContent()), "BookFragmentItem");
				fragmentTransaction.commit();
				setTitle(list.get(0).getTitle());
			} else {
				String result = HttpUtils.doGet(AppContext.load_books_url);
				if (StringUtil.isNotBlank(result)) {
					String booksUrl[] = result.split(",");
					for (final String url : booksUrl) {
						save(url, bt);
					}
				}
				handler.sendEmptyMessage(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void save(String path, BookTable bt) throws Exception {
		BookEntity entity = new BookTable(this).new BookEntity();
		InputStream inStream = null;
		HttpGet httpRequest = new HttpGet(path);
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 6000);
		HttpResponse httpResponse = httpClient.execute(httpRequest);
		
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			inStream = httpResponse.getEntity().getContent();
			StringBuilder sb = new StringBuilder();
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "gbk"));
				String line = null;
				String title = reader.readLine();
				entity.setTitle(title);
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				byte[] content = sb.toString().getBytes();
				entity.setContent(content);
				bt.save(entity);
			} catch (IOException e) {
				sb.delete(0, sb.length());
			} finally {
				HttpUtils.closeStream(inStream);
			}
		} else {
			throw new Exception("conn exception");
		}
	}
	/**
	 * 初始化Sliding Menu
	 */
	private void initSlidingMenu() {
		// customize the SlidingMenu
		sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setBehindOffset(CanvasWidth / 4);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (sm.isMenuShowing()) {
				toggle();
			} else {
				return super.onKeyDown(keyCode, event);
			}
		}
		return true;
	}
	@Override
	public boolean handleMessage(Message msg) {
		try {
			BookTable bt = new BookTable(this);
			list = bt.get();
			fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
			Fragment bookSliding = new BookSlidingSettingFragment();
			fragmentTransaction.replace(R.id.menu_frame, bookSliding);
			if (list != null && !list.isEmpty()) {
				setTitle(list.get(0).getTitle());
				fragmentTransaction.replace(R.id.content, new BookFragmentItem(list.get(0).getContent()), "BookFragmentItem");
			}
			fragmentTransaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
